package com.lhd.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.lhd.config.JwtConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;
@Component
public class JwtUtil {
    @Autowired
    private JwtConfig jwtConfig;
	//接收业务数据(载荷中的内容),生成token并返回
    public String genToken(Map<String, Object> claims) {
        return JWT.create()
                .withClaim("claims", claims)
                .withExpiresAt(new Date(System.currentTimeMillis() + jwtConfig.getExpirationTimeMs()))
                .sign(Algorithm.HMAC256(jwtConfig.getSecretKey()));
    }

	//接收token,验证token,并返回业务数据 丢出异常则验证失败 反之成功
    public Map<String, Object> parseToken(String token) {
        return JWT.require(Algorithm.HMAC256(jwtConfig.getSecretKey()))
                .build()
                .verify(token)
                .getClaim("claims")
                .asMap();
    }
}
